<template>
  <div class="flex flex-wrap">
    <!-- 左侧部门列表 -->
    <div class="w-[25%]">
      <LeftCard @search-department="searchDepartmentList" />
    </div>
    <!-- 右侧表单/表格 -->
    <div class="w-[75%]">
      <!-- 表单 -->
      <FosoCard :showheader="false" class="!pl-0">
        <TopForm @search="searchUserHandle" />
      </FosoCard>
      <!-- 表格 -->
      <FosoTable
        ref="userTable"
        :columns="columns"
        :request-api="getUserListData"
        :toolbarbutton-name="$t('sys.user.addUser')"
        class="!h-[1050px] pr-4"
        @add="openDrawerHandle('add', $event)"
        @delete="DeleteHandle($event)"
        @edit="openDrawerHandle('edit', $event)"
      >
        <template #extraActionButtons="{ row }">
          <!-- 登出按钮 -->
          <el-button
            :icon="SwitchButton"
            link
            type="danger"
            @click="exitHandle(row)"
          />
        </template>
      </FosoTable>
    </div>
    <!-- 弹窗框 -->
    <Drawer class="w-[40%]" @refresh="reloadTable" />
  </div>
</template>

<script setup lang="tsx">
import type { UserInfo } from '#/api/sys/model/userModel';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { SwitchButton } from '@element-plus/icons-vue';

import { deleteUser, getUserList, updateUser } from '#/api/sys/user';
import switchCom from '#/components/FosoSwitch/index.vue';

import { ExtraDrawer, LeftCard, TopForm } from './components';

import 'element-plus/es/components/tag/style/css';

const userTableRef = useTemplateRef('userTable');
const formData = ref({
  departmentId: 1,
});

/**
 * @author Buke
 * @description 获取用户列表数据
 * @param params
 */
const getUserListData = async (params: any) => {
  const { page = 1, pageSize = 5 } = params;
  const res: any = await getUserList({ page, pageSize, ...formData.value });
  return {
    total: res.data.length,
    items: res.data,
  };
};
// 弹窗连接
const [Drawer, drawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: ExtraDrawer,
});

const columns = computed(() => [
  {
    type: 'checkbox',
    width: 120,
  },
  { field: 'username', title: $t('sys.login.username'), treeNode: true },
  { field: 'nickname', title: $t('sys.user.nickname') },
  {
    field: 'email',
    sortable: true,
    title: $t('sys.login.email'),
  },
  {
    field: 'updatedAt',
    title: $t('sys.menu.createTime'),
    formatter: ['formatDate', 'yyyy-MM-dd'],
  },
  {
    field: 'status',
    title: $t('sys.menu.status'),
    slots: {
      default: ({ row }: { row: any }) => {
        return h(switchCom, {
          // 1：启动 0：禁用
          status: row.status,
          'onUpdate:status': async (value: any) => {
            await updateUser({
              id: row.id,
              status: value,
            }).then(() => {
              ElMessage.success('修改成功');
            });
            row.status = value; // 修改数据类型
          },
        });
      },
    },
  },
  {
    field: 'status66',
    title: $t('sys.menu.operation'),
    width: 300,
    slots: { default: 'action' },
  },
]);

/**
 * @author Buke
 * @description 打开弹窗
 * @param {string} type - 操作类型，'edit' 表示编辑，'add' 表示新增。
 * @param {UserInfo} row - 要编辑的行数据对象，包含字典相关信息。
 * @returns {void}
 */
const openDrawerHandle = (type: string, row?: UserInfo): void => {
  if (type === 'edit') {
    drawerApi.setState({ title: $t('sys.role.editRole') });
    drawerApi.setData({ type: 'editData', id: row.id });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
  if (type === 'add') {
    drawerApi.setState({ title: $t('sys.user.addUser') });
    drawerApi.setData({ type: 'addData' });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
};

/**
 * @author Buke
 * @deprecated 登出操作
 */
const exitHandle = (row: UserInfo) => {
  ElMessage.success(`登出: ${row.username}`);
};

/**
 * @author Buke
 * @description 删除字典
 * @param {any} row - 要删除的行数据。
 * @returns {void}
 */
async function DeleteHandle(row: UserInfo): Promise<void> {
  try {
    await deleteUser(row.id as number);
    ElMessage.success('删除成功');
    userTableRef.value?.gridApi.reload();
  } catch {
    ElMessage.error('删除失败');
  }
}

/**
 * @author Buke
 * @description 搜索用户
 * @param {any} params - 搜索参数。
 * @returns {void}
 * @todo 用户搜索功能待完善
 */
const searchUserHandle = async (params: any): Promise<void> => {
  formData.value = params;
  await userTableRef.value?.gridApi.query();
};

/**
 * @author Buke
 * @description 处理表格数据加载完成后的操作，如更新表格数据。
 * @returns {void}
 */
const reloadTable = (): void => {
  userTableRef.value?.gridApi.reload();
  drawerApi.close();
};

/**
 * @description 搜索部门列表
 */
const searchDepartmentList = async (data: any) => {
  formData.value.departmentId = data.id;
  await userTableRef.value?.gridApi.query();
};
</script>
